package com.recsmile.sgs.core.net.codec;

import com.recsmile.sgs.util.CommandManager;
import com.recsmile.sgs.util.SerializableUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by hanyuanliang on 16/8/24.
 */
public class ProtoBufDecoder extends ByteToMessageDecoder
{
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        ByteBuf buf = Unpooled.copiedBuffer(in);
        short code = buf.readShort();
        Class<?> cls =  CommandManager.find(code);
        if(cls == null){
            System.out.println("......"+code);
        }else {
            byte[] array = new byte[buf.readableBytes()];
            buf.readBytes(array, buf.arrayOffset(), buf.readableBytes());
            //System.out.println(Arrays.toString(array));
            out.add(SerializableUtil.newInstance(array,cls));
        }
    }
}
